package com.example.nonggo.view.act;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.allen.library.RxHttpUtils;
import com.allen.library.interceptor.Transformer;
import com.bumptech.glide.Glide;
import com.example.nonggo.Constants;
import com.example.nonggo.R;
import com.example.nonggo.api.BaseApi;
import com.example.nonggo.api.MDataObserver;
import com.example.nonggo.bean.AiWeatherRes;
import com.example.nonggo.bean.Forecast15DaysRes;
import com.example.nonggo.bean.Weather24HoursRes;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.tencent.mmkv.MMKV;

import org.json.JSONException;
import org.json.JSONObject;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class WeatherDetailActivity extends AppCompatActivity {
    public final String token =  MMKV.defaultMMKV().getString(Constants.ACCESS_TOKEN,"0");
    private TextView tv_temp;
    private TextView tv_weather;
    private TextView iv_area;
    private ImageView iv_weather;
    private TextView tv_heavy_shower;
    private TextView tv_wind_speed;
    private TextView tv_direction;
    private TextView tv_update_time;
    private TextView tv_max_temp;
    private TextView tv_min_temp;
    private TextView tv_rain;
    private TextView tv_humidity;
    private TextView tv_wind;

    public final String city =  MMKV.defaultMMKV().getString(Constants.CITY,"广州市");
    public final String county =  MMKV.defaultMMKV().getString(Constants.COUNTY,"天河区");
    public final String province =  MMKV.defaultMMKV().getString(Constants.PROVINCE,"广东省");
    private LineChart lineChart;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        getWindow().setNavigationBarColor(Color.TRANSPARENT);
        // 隐藏状态栏
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        setContentView(R.layout.activity_weather_detail);
        tv_temp = findViewById(R.id.tv_temp);
        tv_weather = findViewById(R.id.tv_weather);
        iv_area = findViewById(R.id.iv_area);
        iv_weather = findViewById(R.id.iv_weather);
        tv_heavy_shower = findViewById(R.id.tv_heavy_shower);
        tv_wind_speed = findViewById(R.id.tv_wind_speed);
        tv_direction = findViewById(R.id.tv_direction);
        tv_update_time = findViewById(R.id.tv_update_time);
        tv_max_temp = findViewById(R.id.tv_max_temp);
        tv_min_temp = findViewById(R.id.tv_min_temp);
        tv_rain = findViewById(R.id.tv_rain);
        tv_humidity = findViewById(R.id.tv_humidity);
        tv_wind = findViewById(R.id.tv_wind);
        tv_temp.setText(MMKV.defaultMMKV().getString(Constants.TEMP,"")+"℃");
        tv_weather.setText(MMKV.defaultMMKV().getString(Constants.CONDITION,""));
        iv_area.setText(MMKV.defaultMMKV().getString(Constants.FULL_NAME,"广东省-广州市-天河区"));
        tv_heavy_shower.setText(MMKV.defaultMMKV().getString(Constants.PRECIPITATION,"0")+"mm");
        tv_wind_speed.setText(MMKV.defaultMMKV().getString(Constants.WIND_SPEED,"")+"千米/小时");
        tv_direction.setText(MMKV.defaultMMKV().getString(Constants.WIND_DIR,""));
        tv_update_time.setText(MMKV.defaultMMKV().getString(Constants.UPDATE_TIME,"")+"更新");
          lineChart = findViewById(R.id.lineChart);
//        setupChart(lineChart);
        Glide.with(this).load(MMKV.defaultMMKV().getString(Constants.WEATHER_LOGO,"")).into(iv_weather);
        get24HourDate();
        getForecast15Days();
    }





    private void get24HourDate(){
        RxHttpUtils.
                createApi(BaseApi.class).get24HoursWeatherData("Bearer "+token, getBody() )
                .compose(Transformer.switchSchedulers(null))
                .subscribe(new MDataObserver<Weather24HoursRes>() {

                    @Override
                    protected void onSuccess(Weather24HoursRes data) {
                        tv_max_temp.setText(data.getMaxTemp()+"℃");
                        tv_min_temp.setText(data.getMinTemp()+"℃");
                        tv_rain.setText(data.getMaxPop()+"mm");
                        tv_humidity.setText(data.getMaxHumidity()+"%");
                        tv_wind.setText(data.getMaxHumidity()+"千米/小时");
                    }
                });

    }
    private void getForecast15Days(){
        RxHttpUtils.
                createApi(BaseApi.class).getForecast15Days("Bearer "+token, getBody() )
                .compose(Transformer.switchSchedulers(null))
                .subscribe(new MDataObserver<Forecast15DaysRes>() {

                    @Override
                    protected void onSuccess(Forecast15DaysRes data) {
                        // 生成日期数据
                        List<String> dates = generateDates(data.getForecast());

                        // 生成温度数据
                        List<Entry> dayEntries = new ArrayList<>();
                        List<Entry> nightEntries = new ArrayList<>();
                        for (int i = 0; i < 7; i++) {
                            dayEntries.add(new Entry(i,data.getForecast().get(i).getTempDay())); // 白天温度
                            nightEntries.add(new Entry(i, data.getForecast().get(i).getTempNight())); // 夜间温度
                        }
                        LineDataSet dayDataSet = createDataSet(dayEntries, "白天最高温度", Color.BLUE);
                        LineDataSet nightDataSet = createDataSet(nightEntries, "夜间最低温度", Color.GREEN);
                        // 组合数据
                        LineData lineData = new LineData(dayDataSet, nightDataSet);
                        //设置标题字体
                        Legend legend = lineChart.getLegend();
                        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
                        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
                        legend.setTextSize(20f);
                        legend.setYOffset(30f);
                        // 配置图表
                        lineChart.setExtraOffsets(0, 0, 0, 30);
                        lineChart.setData(lineData);
                        configureAxis(lineChart , dates);
                        lineChart.invalidate(); // 刷新图表
                    }
                });

    }
    // 自定义日期格式化器
    private static class DateAxisFormatter extends ValueFormatter {
        private final List<String> dates;

        public DateAxisFormatter(List<String> dates) {
            this.dates = dates;
        }

        @Override
        public String getFormattedValue(float value) {
            int index = (int) value;
            if (index >= 0 && index < dates.size()) {
                return dates.get(index);
            }
            return "";
        }
    }
    private void configureAxis(LineChart chart, List<String> dates) {
        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new DateAxisFormatter(dates));
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(7);
        xAxis.setTextSize(20f);
        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setAxisMinimum(0f);
        leftAxis.setAxisMaximum(50f);
        leftAxis.setGranularity(10f);
        leftAxis.setLabelCount(6, true);
        leftAxis.setTextSize(40f);
        chart.getAxisRight().setEnabled(false); // 禁用右侧Y轴
        chart.getDescription().setEnabled(false); // 隐藏描述
        chart.setDragEnabled(false); // 启用拖动手势
        chart.setScaleEnabled(false); // 启用缩放
    }
    private LineDataSet createDataSet(List<Entry> entries, String label, int color) {
        LineDataSet dataSet = new LineDataSet(entries, label);
        dataSet.setColor(color);
        dataSet.setLineWidth(2f);
        dataSet.setCircleRadius(4f);
        dataSet.setCircleColor(color);
        dataSet.setValueTextSize(12f);
        dataSet.setDrawValues(true); // 数值标签
        return dataSet;
    }
    private List<String> generateDates(List<Forecast15DaysRes.Forecast> forecast) {
        List<String> dates = new ArrayList<>();

        for (int i =0;i<forecast.size();i++){
            String[] parts =  forecast.get(i).getPredictDate().split("-");
            int month = Integer.parseInt(parts[1]); // 直接获取03转3
            int day = Integer.parseInt(parts[2]);
            String d = month+"-"+day;
            dates.add(d);
        }
        return dates;
    }

    private RequestBody getBody() {
        JSONObject jb = new JSONObject();
        try {

            jb.put("province", province);
            jb.put("city", city);
            jb.put("county", county);


        } catch (JSONException e) {
            e.printStackTrace();
        }
        return getRequestBody(jb);
    }
    public   RequestBody getRequestBody(JSONObject jb) {
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jb.toString());
    }
}